const Router = require('koa-router')
const Order = require('../schema/Order')
const OrderNo = require('../schema/OrderNo')
const tools = require('../utils/tools')

const orderRouter = new Router({
  prefix: '/nodeApi/order'
})

orderRouter.put('/new', async ctx => {
  let order = ctx.request.body
  let payload = tools.decode(ctx.header.authorization).payload;
  order.opCode = payload.opCode;
  order.opName = payload.opName;
  let id = await OrderNo.findOneAndUpdate({ $inc: { id: 1 }})
  order.orderNo = id.id 
  await new Order(order).save()
  ctx.body = {
    result: 'success'
  }
})

orderRouter.get('/now', async ctx => {
  let payload = tools.decode(ctx.header.authorization).payload;
  let opCode = payload.opCode;
  if (opCode) {
    let order = await Order.findOne({
      opCode: opCode,
      orderState: '订单已提交'
    })
    ctx.body = order;
  } else {
    ctx.body = {
      result: 'fail'
    }
  }
})

orderRouter.post('/now/update', async ctx => {
  let payload = tools.decode(ctx.header.authorization).payload;
  let body = ctx.request.body;
  let opCode = payload.opCode;
  let order = await Order.findOne({
    opCode: opCode,
    orderState: '订单已提交'
  })
  delete body.__v;
  order.set(body);
  await order.save();
  ctx.body = {
    result: 'success'
  }
})
orderRouter.get('/history', async ctx => {
  let payload = tools.decode(ctx.header.authorization).payload;
  let opCode = payload.opCode;
  let offset = ctx.query.offset;
  if (opCode && offset) {
    let orders = await Order.paginate({
      opCode: opCode,
      orderState: '订单已确认'
    }, {
      offset: offset,
      limit: 20,
      sort: '-generateTime'
    })
    ctx.body = orders;
  } else {
    ctx.body = {
      result: 'fail'
    }
  }
})
// admin
orderRouter.get('/admin/now/list', async ctx => {
  let page = ctx.query.page;
  let limit = ctx.query.limit;
  if (page && limit) {
    let orders = await Order.paginate({
      orderState: '订单已提交'
    }, {
      page: page,
      limit: limit
    })
    ctx.body = orders;
  } else {
    ctx.status = 400
    ctx.body = {
      result: 'fail'
    }
  }
})

orderRouter.post('/admin/submit', async ctx => {
  let orders = ctx.request.body
  if (orders && orders.length > 0) {
    await Order.updateMany({
      orderNo: orders
    }, {
      $set: {
        orderState: '订单已确认'
      }
    })
    ctx.body = {
      result: 'success'
    }
  } else {
    ctx.status = 400
    ctx.body = {
      result: 'fail'
    }
  }
})

module.exports = orderRouter